from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm

from learning.models import TeacherAnnouncement, TeacherAssignment


class StudentRegistrationForm(UserCreationForm):
    full_name = forms.CharField(
        label="姓名",
        max_length=150,
        help_text="请输入真实姓名，方便老师识别你。",
    )
    teacher_username = forms.CharField(
        label="指导老师账号",
        required=False,
        help_text="可选。如果填写，将自动关联到该老师。",
    )

    class Meta(UserCreationForm.Meta):
        model = get_user_model()
        fields = ("username", "full_name", "teacher_username", "password1", "password2")

    def clean_teacher_username(self):
        username = self.cleaned_data.get("teacher_username", "").strip()
        if not username:
            return None

        User = get_user_model()
        try:
            teacher = User.objects.get(username=username, role=User.Role.TEACHER)
        except User.DoesNotExist as exc:
            raise forms.ValidationError("指定的老师不存在，请确认教师帐号。") from exc
        return teacher

    def save(self, commit=True):
        user = super().save(commit=False)
        full_name = self.cleaned_data.get("full_name", "").strip()
        if full_name:
            parts = full_name.split(None, 1)
            user.first_name = parts[0]
            if len(parts) > 1:
                user.last_name = parts[1]
        user.role = user.Role.STUDENT
        teacher = self.cleaned_data.get("teacher_username")
        if teacher:
            user.assigned_teacher = teacher
        if commit:
            user.save()
        return user


class ProfileForm(forms.ModelForm):
    full_name = forms.CharField(
        label="姓名",
        required=False,
        max_length=150,
        help_text="更新你的显示名称，方便老师识别你。",
    )

    class Meta:
        model = get_user_model()
        fields = ("full_name", "email")
        widgets = {
            "email": forms.EmailInput(attrs={"placeholder": "name@example.com"}),
        }
        labels = {
            "email": "邮箱",
        }

    def __init__(self, *args, **kwargs):
        instance = kwargs.get("instance")
        initial = kwargs.setdefault("initial", {})
        if instance:
            initial["full_name"] = " ".join(
                part for part in [instance.first_name, instance.last_name] if part
            )
        super().__init__(*args, **kwargs)
        self.fields["full_name"].widget.attrs.update(
            {"placeholder": "例如：王小明", "autocomplete": "name"}
        )
        self.fields["email"].widget.attrs.update(
            {"autocomplete": "email", "placeholder": "name@example.com"}
        )

    def save(self, commit=True):
        user = super().save(commit=False)
        full_name = self.cleaned_data.get("full_name", "").strip()
        if full_name:
            parts = full_name.split(None, 1)
            user.first_name = parts[0]
            user.last_name = parts[1] if len(parts) > 1 else ""
        else:
            user.first_name = ""
            user.last_name = ""
        if commit:
            user.save(update_fields=["first_name", "last_name", "email"])
        return user


class TeacherStudentLinkForm(forms.Form):
    student_username = forms.CharField(
        label="学生用户名",
        help_text="输入学生在平台的用户名，将其关联到你的班级。",
    )

    def __init__(self, *args, teacher, **kwargs):
        super().__init__(*args, **kwargs)
        self.teacher = teacher
        self.user_model = get_user_model()
        self.fields["student_username"].widget.attrs.update(
            {
                "placeholder": "例如：student001",
                "autocomplete": "off",
            }
        )

    def clean_student_username(self):
        username = self.cleaned_data["student_username"].strip()
        try:
            student = self.user_model.objects.get(
                username=username,
                role=self.user_model.Role.STUDENT,
            )
        except self.user_model.DoesNotExist as exc:
            raise forms.ValidationError("未找到该学生账号，请确认用户名。") from exc

        if student.assigned_teacher and student.assigned_teacher != self.teacher:
            raise forms.ValidationError("该学生已由其他老师管理。")
        self.student = student
        return username

    def save(self):
        self.student.assigned_teacher = self.teacher
        self.student.save(update_fields=["assigned_teacher"])
        return self.student


class TeacherAnnouncementForm(forms.ModelForm):
    class Meta:
        model = TeacherAnnouncement
        fields = ("title", "content")
        labels = {
            "title": "公告标题",
            "content": "公告内容",
        }
        widgets = {
            "content": forms.Textarea(attrs={"rows": 4}),
        }

    def __init__(self, *args, teacher, **kwargs):
        super().__init__(*args, **kwargs)
        self.teacher = teacher

    def save(self, commit=True):
        announcement = super().save(commit=False)
        announcement.teacher = self.teacher
        if commit:
            announcement.save()
        return announcement


class TeacherAssignmentForm(forms.ModelForm):
    class Meta:
        model = TeacherAssignment
        fields = ("title", "description", "due_date")
        labels = {
            "title": "作业主题",
            "description": "作业要求",
            "due_date": "截止日期",
        }
        widgets = {
            "description": forms.Textarea(attrs={"rows": 4}),
            "due_date": forms.DateInput(attrs={"type": "date"}),
        }
        help_texts = {
            "due_date": "可选，不填写则表示自行安排完成时间。",
        }

    def __init__(self, *args, teacher, **kwargs):
        super().__init__(*args, **kwargs)
        self.teacher = teacher

    def save(self, commit=True):
        assignment = super().save(commit=False)
        assignment.teacher = self.teacher
        if commit:
            assignment.save()
        return assignment


class AssignmentSubmissionForm(forms.Form):
    content = forms.CharField(
        label="提交内容",
        required=False,
        widget=forms.Textarea(attrs={"rows": 4, "placeholder": "可填写完成情况、疑问等"}),
    )
